package com.aduerr.v1shouyin.unioncard;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.common.Constants;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.aduerr.v1shouyin.view.SecurityCodeView;
import com.google.gson.Gson;
import com.orhanobut.hawk.Hawk;
import com.yeahka.shouyintong.sdk.action.PosSign;
import com.yeahka.shouyintong.sdk.action.ReprintTicket;
import com.yeahka.shouyintong.sdk.action.SwipeCardRefund;
import com.yeahka.shouyintong.sdk.action.SwipeCardTrans;
import com.yeahka.shouyintong.sdk.api.SytApi;
import com.yeahka.shouyintong.sdk.api.SytFactory;
import com.yeahka.shouyintong.sdk.excep.ActionIllegalException;
import com.yeahka.shouyintong.sdk.info.TradeInfo;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author HI
 * @email dev1024@foxmail.com
 * @time 2019/7/17 18:10
 * @change
 * @chang time
 * @class describe
 */

public class UnionTranscationDetailActivity extends BaseUnionActivity {


    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_state)
    TextView tvState;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_card_no)
    TextView tvCardNo;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_voucher_no)
    TextView tvVoucherNo;
    @BindView(R.id.tv_order_id)
    TextView tvOrderId;
    @BindView(R.id.tv_reference_id)
    TextView tvReferenceId;
    @BindView(R.id.bt_confirm)
    Button btConfirm;
    @BindView(R.id.bt_print)
    Button btPrint;

    private TradeInfo tradeInfo;

    private SytApi sytApi;

    BroadcastReceiver broadcastReceive = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(TextUtils.equals(action, Constants.ACTION)) {
                try {
                    sytApi.handleAction(intent, baseResp -> {
                        if(baseResp.isSuccessful()) {
                            if(baseResp instanceof SwipeCardRefund.Resp) {
                                //退款
                                ToastUtils.showToast(UnionTranscationDetailActivity
                                                .this,
                                        "退款成功");
                                finish();
                            } else if(baseResp instanceof PosSign.Resp) {
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                Hawk.put("signTime", sdf.format(new Date()));
                                Hawk.put("unionMerchantId",
                                        ((PosSign.Resp) baseResp).merchantId);
                                //签到
                                Intent intentSign =
                                        new Intent(UnionTranscationDetailActivity.this,
                                        UnionSignInActivity.class);
                                intentSign.putExtra("resp", baseResp);
                                startActivity(intentSign);
                            }
                        } else {
                            if(baseResp instanceof SwipeCardRefund.Resp) {
                                //退款
                                if(TextUtils.equals(((SwipeCardTrans.Resp) baseResp).tradeInfo.getAnswerCode(), "B2")) {
                                    ToastUtils.showToast(UnionTranscationDetailActivity.this, "状态异常，签到后再进行操作");
                                    sign();
                                } else {
                                    ToastUtils.showToast(UnionTranscationDetailActivity.this,
                                            baseResp.getMsg() + "，" + baseResp.getCode());
                                }
                            }
                        }
                    });
                } catch(ActionIllegalException e) {
                    e.printStackTrace();
                }catch(Exception e){
                    Log.i("UNIONEXCEPTION",e.getMessage()+"");
                }
            }
        }

    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_union_transcaion_detail;
    }

    @Override
    protected void initBase() {
        super.initBase();
        ButterKnife.bind(this);
        tvTitle.setText("交易详情");
        sytApi = SytFactory.createSytIml(this);

        tradeInfo = (TradeInfo) getIntent().getSerializableExtra("tradeInfo");
        initData();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION);
        registerReceiver(broadcastReceive, intentFilter);
    }

    private void initData() {
        if(tradeInfo.getTransactionType() == 5) {
            //刷卡交易
            if(TextUtils.isEmpty(tradeInfo.getReferenceNo())) {
                tvState.setText("消费已取消");
                btPrint.setVisibility(View.GONE);
            } else {
                tvState.setText("消费成功");
                btPrint.setVisibility(View.VISIBLE);
            }
            tvType.setText("消费");
            btConfirm.setVisibility(View.VISIBLE);
        } else if(tradeInfo.getTransactionType() == 4) {
            //刷卡退款
            if(TextUtils.isEmpty(tradeInfo.getReferenceNo())) {
                tvState.setText("退款已取消");
                btPrint.setVisibility(View.GONE);
            } else {
                tvState.setText("退款成功");
                btPrint.setVisibility(View.VISIBLE);
            }
            tvType.setText("退款");
            btConfirm.setVisibility(View.GONE);
        } else if(tradeInfo.getTransactionType() == 10) {
            //预授权
            if(TextUtils.isEmpty(tradeInfo.getReferenceNo())) {
                tvState.setText("预授权已取消");
                btPrint.setVisibility(View.GONE);
            } else {
                tvState.setText("预授权成功");
                btPrint.setVisibility(View.VISIBLE);
            }
            tvType.setText("预授权");
            btConfirm.setVisibility(View.GONE);
        } else if(tradeInfo.getTransactionType() == 11) {
            //预授权撤销
            if(TextUtils.isEmpty(tradeInfo.getReferenceNo())) {
                tvState.setText("预授权撤销已取消");
                btPrint.setVisibility(View.GONE);
            } else {
                tvState.setText("预授权撤销成功");
                btPrint.setVisibility(View.VISIBLE);
            }
            tvType.setText("预授权撤销");
            btConfirm.setVisibility(View.GONE);
        } else if(tradeInfo.getTransactionType() == 20) {
            //预授权完成
            if(TextUtils.isEmpty(tradeInfo.getReferenceNo())) {
                tvState.setText("预授权完成已取消");
                btPrint.setVisibility(View.GONE);
            } else {
                tvState.setText("预授权完成成功");
                btPrint.setVisibility(View.VISIBLE);
            }
            tvType.setText("预授权完成");
            btConfirm.setVisibility(View.GONE);
        } else if(tradeInfo.getTransactionType() == 21) {
            //预授权完成撤销
            if(TextUtils.isEmpty(tradeInfo.getReferenceNo())) {
                tvState.setText("预授权完成撤销已取消");
                btPrint.setVisibility(View.GONE);
            } else {
                tvState.setText("预授权完成撤销成功");
                btPrint.setVisibility(View.VISIBLE);
            }
            tvType.setText("预授权完成撤销");
            btConfirm.setVisibility(View.GONE);
        }
        tvMoney.setText((Float.parseFloat(tradeInfo.getAmount() + "") / 100) + "");
        tvCardNo.setText(tradeInfo.getCardNo());
        tvDate.setText(tradeInfo.getDate());
        tvTime.setText(new StringBuffer(tradeInfo.getTime().substring(0, 4)).insert(2,
                ":"));
        tvVoucherNo.setText(tradeInfo.getFlowId());
        tvOrderId.setText(tradeInfo.getOrderId());
        tvReferenceId.setText(tradeInfo.getReferenceNo());
    }

    private void sign() {
        PosSign.Req req = new PosSign.Req();
        sytApi.sendReq(req);
    }

    private void showDialog() {
        View view =
                LayoutInflater.from(UnionTranscationDetailActivity.this).inflate(R.layout.dialog_tuikuan, null);
        // 对话框
        Dialog dialog = new Dialog(UnionTranscationDetailActivity.this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(0));
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.show();
        // 设置宽度为屏幕的宽度
        WindowManager windowManager = this.getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); // 设置宽度
        dialog.getWindow().setAttributes(lp);
        dialog.getWindow().setContentView(view);
        //==================================弹出键盘================================================================
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        //===========================================================================================================
        //findview
        //找到自定义的控件用来显示密码
        SecurityCodeView securityCodeView =
                (SecurityCodeView) view.findViewById(R.id.scv_edittext);
        securityCodeView.setInputCompleteListener(new SecurityCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                dialog.hide();
                SwipeCardRefund.Req swipeRefund = new SwipeCardRefund.Req();
                System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>swipeRefund>>"+new Gson().toJson(swipeRefund));
                swipeRefund.oriOrderId = tradeInfo.getOrderId();
                swipeRefund.referenceNo = tradeInfo.getReferenceNo();
                swipeRefund.amount = (int) tradeInfo.getAmount();
                sytApi.sendReq(swipeRefund);
            }

            @Override
            public void deleteContent(boolean isDelete) {
                //DO NO THING
            }
        });
    }



    @OnClick({R.id.img_back, R.id.bt_confirm, R.id.bt_print})
    public void onViewClicked(View view) {
        switch(view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.bt_confirm:
                showDialog();
                break;
            case R.id.bt_print:
                print();
                break;
        }
    }

    private void print() {
        ReprintTicket.Req req = new ReprintTicket.Req();
        req.orderId = tradeInfo.getOrderId();
        req.referenceNo = tradeInfo.getReferenceNo();
        req.transType = tradeInfo.getTransactionType();
        sytApi.sendReq(req);
    }


    @Override
    public void onDestroy() {
        try {
            unregisterReceiver(broadcastReceive);
        } catch(Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }

}
